package cn.com.pansky.action.myaccount;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;
import cn.com.pansky.service.UserService;
import cn.com.pansky.util.DateUtil;
import cn.com.pansky.util.EncryptionUtils;
import cn.com.pansky.util.MD5Util;
import cn.com.pansky.util.ProtectUtil;

@Component
public class LoginAction extends CommonAction {
	
	@Value("${imgPath}")
	String path;
	/**
	 * 用户状态是否锁定
	 */
	public void checkStatus(){
		String findUser = urlConfig.getVar("queryRC10");
		if (SqlHelper.queryOne(findUser) != null) {
			//根据手机号获取用户信息
			String getInfo = urlConfig.getVar("getInfo");
			Model model = SqlHelper.queryOne(getInfo);
			//用户状态
			String AA005 = model.getString("AA005");
			if (!"0".equals(AA005)) {
				//获取锁定时间
				long AA034 = model.getLong("AA034");
				//当前时间
				long nowTime = new Timestamp(
						System.currentTimeMillis()).getTime();
				//时间差
				double time = (nowTime-AA034)/1000/60/60;
				if (time>24) {
					String unlock = urlConfig.getVar("unlock");
					SqlHelper.execute(unlock);
					checkUser();
				}else{
					context.putError(101, "账户已锁");
				}
			}else{
				checkUser();
			}
		}else{
			context.putError(102, "账户不存在");
		}
	}
	
	/**
	 * app端登陆
	 */
	public void checkUser(){
		System.out.println("------>"+path);
		//获取用户输入密码
		String password = getParam("AA002");
		String AA032 = getParam("AA032");
		
		String findUserID = urlConfig.getVar("findUserID");
		Model model = SqlHelper.queryOne(findUserID);
			
		String AA001 = model.getString("AA001");
		String findPass = urlConfig.getVar("findPass");
		String AA002 = SqlHelper.queryOne(findPass,AA001).getString("AA002");
		if (MD5Util.string2MD5(password).equals(AA002)) {
			String udid = getParam("XCSUdid");
			String brand = getParam("XCSBrand");
			String models = getParam("XCSModel");
			String os = getParam("XCSSystemName");
			String osVersion = getParam("XCSSystemVersion");
			String bundleID = getParam("XCSBundleID");
			
			String builderNumber = getParam("XCSBuildNumber");
			String appVersion = getParam("XCSAppVersion");
			String ip = context.getRequest().getRemoteAddr();
			
			String findRC11 = urlConfig.getVar("findRC11");
			Model m1 = SqlHelper.queryOne(findRC11, AA001,udid);
			String AF013 = "";
			if (null == m1) {
				String addRC11 = urlConfig.getVar("addRC11");
				SqlHelper.execute(addRC11, AA001,udid,brand,models,os,osVersion,bundleID,builderNumber,appVersion);
				Model m = SqlHelper.queryOne(findRC11, AA001,udid);
				AF013 = m.getString("ID");
			}else{
				AF013 = m1.getString("ID");
			}
			String record = urlConfig.getVar("record");
			SqlHelper.execute(record, AA001,new Timestamp(System.currentTimeMillis()),ip,AF013);
			
//			context.getServletSession().setAttribute("AA032", AA032);//session中保存用户ID
			
			String findUser = urlConfig.getVar("findUser");
			Model m = SqlHelper.queryOne(findUser, AA032);
			context.getServletSession().setAttribute("user",m);//session中保存用户信息
//			用户id + 20161008 + MD5(用户ID + 用户密码 + 20161008)
//			20161008 是用户登录日期
			
			//获取当前用户未读通知条数：
			String sql = "select count(*) NUM from IC52 where USERID = ? and ISREAD = 'N'";
			Model mm = SqlHelper.queryOne(sql, AA001);
			String num = mm.getString("NUM");
			
			String token = AA001+"_"+DateUtil.current8_Time()+"_"+EncryptionUtils.md5(AA001+AA002+DateUtil.current8_Time());
			datas.put("CA003", m.getString("CA003"));
			datas.put("CA006", ProtectUtil.help1(m.getString("CA006")));
			datas.put("AA032", getParam("AA032"));
			datas.put("AA111", model.getInt("AA111"));
			datas.put("AA001", AA001);
			datas.put("token", token);
			datas.put("num", num.equals("0")?"":num);
		}else{
			if (context.getSessionVal("passErr")!=null) {
				Integer num = (Integer) context.getSessionVal("passErr");
				if (num == 2) {
					//密码输入错误3次
					String lock = urlConfig.getVar("lock");
					SqlHelper.execute(lock,new Timestamp(System.currentTimeMillis()).getTime(),AA001);
					context.putError(101, "密码输入错误3次，该账号已锁，请于一天后再尝试登陆！");
					context.getServletSession().removeAttribute("passErr");
				}else{
					context.getServletSession().setAttribute("passErr",(Integer)context.getSessionVal("passErr")+1);
					context.putError(100, "密码输入错误，您还有一次机会，密码输入错误3次，您的账号将会被锁定一天！");
				}
			}else{
				context.getServletSession().setAttribute("passErr",1);
				context.putError(100, "密码输入错误，您还有两次机会，密码输入错误3次，您的账号将会被锁定一天！");
			}
		}
		context.getDatas().put("result", datas);
	}
	
	/**
	 * web端登陆
	 */
	public void checkUser_web(){
		//判断用户验证码是否输入正确
		String sRand = (String) context.getSessionVal("vcode");
		String verification = getParam("verification");
		if (verification.equalsIgnoreCase(sRand)) {
			
			String queryUser = "select AA001, CA001, AA005, AA034, AA003 from RC10 where AA032 = ? AND AA003 = '0'";
			Model queryUser_model = SqlHelper.queryOne(queryUser,getParam("AA032"));
			if (queryUser_model != null) {
				//获取用户输入密码
				String password = getParam("AA002");
				
				String AA001 = queryUser_model.getString("AA001");
				String AA005 = queryUser_model.getString("AA005");
				if (AA005.equals("1")) {
					//获取锁定时间
					long AA034 = queryUser_model.getLong("AA034");
					//当前时间
					long nowTime = new Timestamp(
							System.currentTimeMillis()).getTime();
					//时间差
					double time = (nowTime-AA034)/1000/60/60;
					if (time>24) {
						String unlock = "update RC10 set AA005 = 0, AA034 = ' ' where AA032 = ${AA032} and aa003 = '0'";
						SqlHelper.execute(unlock);
					}else{
						context.putError(101, "账户已锁");
						return;
					}
				} else{
					String findPass = "select AA002 from RA02 where AA001 = ?";
					String AA002 = SqlHelper.queryOne(findPass,AA001).getString("AA002");
					if (MD5Util.string2MD5(password).equals(AA002)) {
						
						context.getServletSession().setAttribute("AA032", getParam("AA032"));//session中保存用户ID
						
						String findUser = "SELECT R1.CA003, R1.CA006, R2.AA001, R2.AA032, R2.AA003 FROM RC03 R1 "
								+ "JOIN (SELECT AA032, AA001, CA001, AA003 FROM RC10 WHERE AA032 = ? and aa003 = '0') R2 "
								+ "ON R1.CA001 = R2.CA001";
						Model m = SqlHelper.queryOne(findUser, getParam("AA032"));
						context.getServletSession().setAttribute("user", m);//session中保存用户信息
						
						datas.put("isPass", true);
						datas.put("CA003", m.getString("CA003"));
						datas.put("CA006", m.getString("CA006"));
						datas.put("AA032", getParam("AA032"));
					}else{
						if (context.getSessionVal("passErr")!=null) {
							Integer num = (Integer) context.getSessionVal("passErr");
							if (num == 2) {
								//密码输入错误3次
								String lock = "update RC10 set AA005 = '1', AA034 = ? where AA001 = ? ";
								SqlHelper.execute(lock,new Timestamp(System.currentTimeMillis()).getTime(),AA001);
								context.putError(101, "密码输入错误3次，该账号已锁，请于一天后再尝试");
								context.getServletSession().removeAttribute("passErr");
							}else{
								context.getServletSession().setAttribute("passErr",(Integer)context.getSessionVal("passErr")+1);
								context.putError(100, "密码输入错误，您还有一次机会，密码输入错误3次，您的账号将会被锁定一天！");
							}
						}else{
							context.getServletSession().setAttribute("passErr",1);
							context.putError(100, "密码输入错误，您还有两次机会，密码输入错误3次，您的账号将会被锁定一天！");
						}
					}
				}
			}else{
				context.putError(102, "账户不存在");
			}
		}else{
			datas.put("isPass", false);
			datas.put("info", "验证码输入有误，请核对后重新输入");
		}
		
		context.getDatas().put("result", datas);
	}
	
	/**
	 * 登录
	 */
	public void autoLogin(){
		String token = getParam("token");
		UserService us = new UserService();
		us.autoLogin(token);
	}
	
	/*
	 * 发送验证码
	 */
	public void sendCode(){
		UserService us = new UserService();
		String AA032 = getParam("AA032");
		us.sendLoginCode(AA032, "0"); //个人用户
	}
	
	/**
	 * 动态验证码登录
	 * @throws Exception
	 */
	public void codeLogin() throws Exception {
		String AA032 = (String) context.getServletSession().getAttribute("AA032");
		if(null == AA032) {
			context.putError(100, "请点击发送验证码！");
			return;
		}
			
		String AA032_ = getParam("AA032");
		if(!AA032.equals(AA032_)) {
			context.putError(100, "手机号与接收验证码手机号不一致");
			return;
		}
		if (AA032!=null && context.getSessionVal("AF016")!=null) {
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF017 desc) where rownum = 1", 
					AA032, getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					context.putError(100, "验证码超时");
				}else{
					//处理登录
					String findUser = "SELECT R1.CA003, R1.CA006, R2.AA001, R2.AA032, R2.AA111, R2.AA003 FROM RC03 R1 "
							+ "JOIN (SELECT AA032, AA001, CA001, AA111, AA003 FROM RC10 WHERE AA032 = ? AND AA003 = '0') R2 "
							+ "ON R1.CA001 = R2.CA001";
					Model m_ = SqlHelper.queryOne(findUser, AA032);
					m_.put("CA006", ProtectUtil.help1(m_.getString("CA006")));
					context.getServletSession().setAttribute("user",m_);//session中保存用户信息
					context.getDatas().put("result", m_);
					context.getServletSession().removeAttribute("AF016");
					context.getServletSession().removeAttribute("AA032");
				}
			} else {
				context.putError(100, "验证码输入错误");
			}
		}else{
			context.putError(100, "验证码已失效，请重新获取");
		}
	}	
}
